<?php
/**
 * 附件上传
 * @author sean
 * @copyright (c)lishi
 * @version  $Revision 1.0 2020-08-25  21:50
 */
namespace app\helper;

use OSS\OssClient;
use OSS\Core\OssException;

class Oss
{
    /**
     * @var string 保存上传文件根目录
     */
    static public $saveBasePath = '';

    /**
     * @var string 访问uri根地址 # http://xxxx/<uriBase>
     */
    private static $accessKeyId = "LTAI4FzUQPGcMZSJ2iZ1jnwJ";
    private static $accessKeySecret = "Gfchqs1zWDah7YgmuiB9XVjw0wg7So";
    private static $endpoint = "oss-cn-beijing.aliyuncs.com";
    private static $bucket = "lishi-oss";
    private static $client;

    /**
     * @param $uploadFile
     * @param $accessUri
     *  如: upload/aaa/bbb/ccc.jpg
     * @return bool
     * @throws \OSS\Core\OssException
     * @throws \Exception
     */
    public static function init()
    {
        self::$accessKeyId = config('filesystem.disks.aliyun.accessId');
        self::$accessKeySecret = config('filesystem.disks.aliyun.accessSecret');
        self::$endpoint = config('filesystem.disks.aliyun.endpoint');
        self::$bucket = config('filesystem.disks.aliyun.bucket');

        self::$client = new OssClient(self::$accessKeyId, self::$accessKeySecret, self::$endpoint);
    }
    /**
     * $field  img / video /mp3
     * @return Response
     * @param $pathName  本地文件
     * @param $savePath 上传路径
     */
    public static function upload($pathName, $savePath)
    {
        try {
            // 保存文件至oss
            self::init();
            $mime = explode('/', mime_content_type($pathName));
            $res = self::$client->uploadFile(self::$bucket, $mime[0] . '/' . $savePath . '.' . $mime[1], $pathName);
            if($res && isset($res['info'])){
                $result = [
                    'code'=> 200,
                    'data'=>  $savePath . '.' . $mime[1],
                    'msg' => '上传成功'
                ];
            } else {
                $result = [
                    'code'=> 200,
                    'uri' => '',
                    'msg'=> ''
                ];    
            }
        } catch (OssException $e) {
            $result = [
                'code'=> 200,
                'data' => '',
                'msg'=> $e->getMessage(),
            ];
        }

        return $result;
    }
}